const Koa = require('koa');
const app = new Koa();
const Router = require('@koa/router')
const parser = require('koa-parser')
const router = new Router()
const user = require('./routes/user')
const singer = require('./routes/singer')
const song = require('./routes/song')
const cors = require("koa2-cors");
const koajwt = require('koa-jwt')
const {User, Singer, Song} = require("./database/index");
const koaBody = require('koa-body')
const static = require('koa-static');
const path = require('path')
const fs = require('fs')

//使用jwt校验
app.use(
  koajwt({secret: "music"}).unless({
    // 登录接口不需要验证
    path: [/^\/user\/login/,
      /^\/user\/register_edit/,
      /^\/user\/getUser/,
      /^\/uploadSong/,
      /^\/uploadLrc/,
      /^\/uploads/,
      /^\/uploadFile/,
    ],
  })
);

app.use(
  cors({
    origin: function (ctx) {
      //设置允许来自指定域名请求
      // if (ctx.url === '/test') {
      //   return '*'; // 允许来自所有域名请求
      // }
      return "*";
    },
    maxAge: 5, //指定本次预检请求的有效期，单位为秒。
    credentials: true, //是否允许发送Cookie
    allowMethods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"], //设置所允许的HTTP请求方法'
    allowHeaders: ["Content-Type", "Authorization", "Accept"], //设置服务器支持的所有头信息字段
    exposeHeaders: ["WWW-Authenticate", "Server-Authorization"], //设置获取其他自定义字段
  })
);

//上传 使用中间件
app.use(koaBody({
  multipart: true,
  maxFileSize: 1000 * 1024 * 1024,  //设置上传文件最大限制，默认10M
  formidable: {
    // 编写上传目录
    uploadDir: path.join(__dirname, 'public/uploads'),
    // 保留文件扩展名
    keepExtensions: true,
  }
}))

// '当前项目绝对路径'+__dirname;
app.use(static(path.join(__dirname, 'public')))

//上传 单/多 个音频/图片/歌词
//params  用 ctx.request.query接收
//
router.post('/uploadFile', async (ctx) => {
  const files = ctx.request.files.file;
  const {fileType} = ctx.request.query;
  if (fileType == '歌词') {
    //歌词
    const file = ctx.request.files.file
    await new Promise((resolve, reject) => {
      fs.readFile(file.path, (err, data) => {
        resolve(data.toString())
      })
    }).then(res => {
      ctx.body = {
        code: '200',
        msg: 'success',
        data: {
          lyric: res
        }
      }
    })
  } else {
    //多个文件
    const urls = [];
    if (files.length > 1) {
      for (let file of files) {
        const basename = path.basename(file.path);
        const url = {url: `${ctx.origin}/uploads/${basename}`};
        urls.push(url)
      }
      ctx.body = {
        code: '200',
        msg: '上传成功',
        data: urls
      }
    } else {
      //单个文件
      const file = ctx.request.files.file
      const basename = path.basename(file.path)
      ctx.body = {
        code: '200',
        msg: 'success',
        data: {
          "url": `${ctx.origin}/uploads/${basename}`
        }
      }
    }
  }
})


//发送post请求需要，放在路由前面
app.use(parser());
router.use('/user', user.routes())
router.use('/singer', singer.routes())
router.use('/song', song.routes())

/* 调用创建表   一旦创建好，force:false  */
User.sync({force: false})
  .then(() => {
    console.log("用户表创建成功");
  })
  .catch((err) => {
    console.error("用户表创建失败", err);
  });
Song.sync({force: false})
  .then(() => {
    console.log("歌曲表创建成功");
  })
  .catch((err) => {
    console.error("用户表创建失败", err);
  });
Singer.sync({force: false})
  .then(() => {
    console.log("歌手表创建成功");
  })
  .catch((err) => {
    console.error("用户表创建失败", err);
  });


app.use(router.routes())
app.listen(6789, () => {
  console.log(`服务器启动在6789端口：` + 'http://localhost:6789');
})